#include "file.h"
#include <QIODevice>
#include <QFile>
#include <QTextStream>
#include <QDebug>

file::file(){}

//文件读取函数
bool file::readFile(QString address,QStringList& _line)
{
    _line.clear();
    QFile file(address);
    if (!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        qDebug()<<"File can not open at address "<<address;
        QMessageBox::about(NULL,"反馈","数据文件打开失败");
        return false;
    }
    QTextStream in(&file);
    while(!in.atEnd())
    {
        QString line = in.readLine();
        _line.append(line);
    }
    file.close();
    return true;
}


bool file::writeFile(QString address,const QStringList& _line)
{
    QFile file(address+"_temp.csv");
    if(!file.open(QIODevice::Append | QIODevice::Text))
    {
        return false;
    }
    else
    {
        QTextStream out(&file);
        QString temp;
        for(int i=0;i<_line.length();i++)
        {
            temp=temp+_line.at(i)+',';
        }
        temp = temp.left(temp.size()-1);
        out<<temp+'\n';
    }
    file.close();
    return true;
}

bool file::replaceFile(QString address1, QString address2)
{
    QFile file_old(address1+".csv");
    QFile file_new(address2+".csv");
    if (file_old.exists())
    {
       file_old.remove();
       file_new.rename(address1+".csv");
    }
    else
    {
       file_new.rename(address1+".csv");
       file_new.close();
    }
    return true;
}

bool file::modifyFile(QString address, const QStringList &_line)
{
    QStringList temp;
    //
    readFile(address+".csv",temp);
    for (int i=0;i<temp.length();i++)
    {
        QString line=temp.at(i);
        line=line.trimmed();
        QStringList linesplit=line.split(",");
        if(_line.at(1)!=linesplit.at(1))
        {
            QFile file(address+"_temp.csv");
            if(!file.open(QIODevice::Append|QIODevice::Text))
            {
               return false;
            }
            QTextStream out(&file);
            out<<line+"\n";
            file.close();
        }
        else
        {
            writeFile(address,_line);
        }
    }
    replaceFile(address,address+"_temp");
    return true;
}

bool file::appendToFile(QString address, const QStringList &_line)
{
    QFile file(address+".csv");
    if(!file.open(QIODevice::Append | QIODevice::Text))
    {
        return false;
    }
    else
    {
        QTextStream out(&file);
        QString temp;
        for(int i=0;i<_line.length();i++)
        {
            temp=temp+_line.at(i)+',';
        }
        temp = temp.left(temp.size()-1);
        out<<temp+'\n';
    }
    file.close();
    return true;
}
